package com.example.springretry.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.retry.RecoveryCallback;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalTime;

/**
 * @author jimao.zou
 * @date 9/27/2018 2:15 PM
 * @description: TODO
 */
@Service
@Slf4j
public class PayService {
    @Autowired
    private RetryTemplate retryTemplate;


    private static final String SUCCESS = "success";
    private static final String RECOVERY_MESSAGE = "recover";

    private static final int attempt = 3;
    private final int totalNum = 100000;
   /* @Retryable(value = Exception.class,maxAttempts = attempt,backoff = @Backoff(delay = 2000,multiplier = 1.5))
        public int minGoodsnum(int num) throws Exception{
            log.info("minGoodsnum开始"+ LocalTime.now());
            if(num <= 0){
                throw new Exception("数量不对");
            }
            log.info("minGoodsnum执行结束");
            return totalNum - num;
        }

    @Recover
    public int recover(Exception e) {
        log.warn("减库存失败！！！");
        //记日志到数据库
        return totalNum;
    }*/

    public String retryByTemplate(Integer num) throws Exception {
        return retryTemplate.execute(
                new RetryCallback<String, Exception>() {
                    @Override
                    public String doWithRetry(RetryContext context) throws Exception {/*
                        try {
                            retryLogical(num);
                        } catch (RetryException e) {
                            e.printStackTrace();
                        }*/
                            retryLogical(num);

                        return null;
                    }
                },
                new RecoveryCallback<String>() {
                    @Override
                    public String recover(RetryContext context) throws Exception {
                        throw new RetryException("revover logic");
                    }
                }
        );
    }

    private String retryLogical(Integer num) throws RetryException {
        log.info("start logic" + LocalTime.now());
        if (num <= 0) {
            log.warn("trigger retry");
            throw new RetryException("the number is less than zero");
        }
        log.info("end logic");
        return SUCCESS;
    }
}